var fs = require('fs');

var utils = {};

utils.readDirTree = function(path, callback) {
	var results = [];
	fs.readdir(path, function(err, files) {
		if (err) return callback(err);
		var pending = files.length;
		if (!pending) return callback(null, results);
		files.forEach(function(filename) {
			var file = path + '/' + filename;
			fs.stat(file, function(err, stat) {
				if (stat && stat.isDirectory()) {
					utils.readDirTree(file, function(err, files) {
						if (err) return callback(err);
						results.push({
							name: filename,
							files: files
						});
						if (!--pending) callback(null, results);
					});
				} else {
					results.push({name: filename});
					if (!--pending) callback(null, results);
				}
			});
		});
	});
}

utils.dirTreeToFileList = function(dirTree, path) {
	if (path == undefined) {
		path = [];
	}
	var filelist = [];
	dirTree.forEach(function(entry) {
		if (entry.files == undefined) {
			filelist.push(path.concat([entry.name]));
		} else {
			filelist = filelist.concat(utils.dirTreeToFileList(entry.files, path.concat([entry.name])));
		}
	});	
	return filelist;
};

module.exports = utils;